<#
.SYNOPSIS
Flutter GetX Route Generator Script (Fixed encoding issues)

.DESCRIPTION
Generates route table using build_runner, with proper UTF-8 encoding handling
#>

param (
    [switch]$clean = $false  # Whether to perform clean build
)

# 1. Force UTF-8 encoding (fixes Chinese character issues)
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8

# 2. Find project root (where pubspec.yaml exists)
$rootDir = $PWD.Path
while ($rootDir -ne "" -and -not (Test-Path (Join-Path $rootDir "pubspec.yaml"))) {
    $rootDir = Split-Path $rootDir -Parent
}

if (-not $rootDir) {
    Write-Host "[ERROR] Not in a Flutter project (pubspec.yaml not found)" -ForegroundColor Red
    exit 1
}

Set-Location $rootDir
Write-Host "Project root: $rootDir" -ForegroundColor Cyan

# 3. Define route table path
$routeTablePath = "lib/generated/route_table.dart"

# 4. Run build commands
try {
    if ($clean) {
        Write-Host "[INFO] Performing clean build..." -ForegroundColor Magenta
        dart run build_runner clean
        dart run build_runner build --delete-conflicting-outputs
    }
    else {
        if (-not (Test-Path $routeTablePath)) {
            Write-Host "[INFO] Route table not found, performing full build..." -ForegroundColor Yellow
            dart run build_runner build --delete-conflicting-outputs
        }
        else {
            Write-Host "[INFO] Route table exists, performing incremental build..." -ForegroundColor Green
            dart run build_runner build
        }
    }
}
catch {
    Write-Host "[ERROR] Build failed: $_" -ForegroundColor Red
    exit 1
}

# 5. Verify output
if (Test-Path $routeTablePath) {
    Write-Host "[SUCCESS] Route table generated: $routeTablePath" -ForegroundColor Green
    exit 0
}
else {
    Write-Host "[WARNING] No route table detected" -ForegroundColor Yellow
    Write-Host "Possible solutions:"
    Write-Host "1. Check if you have @GetXRoute annotations in your code"
    Write-Host "2. Run with -clean parameter: .\generate_routes.ps1 -clean"
    Write-Host "3. Verify build.yaml configuration"
    exit 1
}